package win.smartown.android.request

import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
import rx.Observable
import java.util.concurrent.TimeUnit

/**
 * Created by smartown on 2017/3/18.
 * <br></br>
 * Description:
 */
object RequestManager {

    private var okHttpClient: OkHttpClient? = null

    @Synchronized fun getOkHttpClient(): OkHttpClient? {
        if (okHttpClient == null) {
            okHttpClient = OkHttpClient.Builder()
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .addInterceptor { chain -> chain.proceed(chain.request()) }
                    .build()
        }
        return okHttpClient
    }

    private fun newRetrofit(baseUrl: String): Retrofit {
        return Retrofit.Builder()
                .client(RequestManager.getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(baseUrl)
                .build()
    }

    object WeatherManager {

        private val baseUrl = "http://v.juhe.cn/weather/"
        private var retrofit: Retrofit? = null

        @Synchronized private fun getRetrofit(): Retrofit {
            if (retrofit == null) {
                retrofit = RequestManager.newRetrofit(baseUrl)
            }
            return retrofit as Retrofit
        }

        fun getWeather(cityname: String, dtype: String, format: String, key: String): Observable<Any> {
            return getRetrofit().create(WeatherService::class.java).getWeather(cityname, dtype, format, key)
        }

    }

    interface WeatherService {

        @GET("index")
        fun getWeather(@Query("cityname") cityname: String, @Query("dtype") dtype: String, @Query("format") format: String, @Query("key") key: String): Observable<Any>

    }

}
